package com.lw.oop.dayfive.cdemo;

import java.sql.*;

/**
 * @author liuwei
 * @ClassName StuInfoTest.java
 * @description: TODO
 * @date 2023年06月20日
 * @version: 1.0
 */
public class StuInfoTest {
    static Statement statement = null;
    static Connection conn;
    static PreparedStatement pstmt = null;
    public void jdbc() throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/jdbc_test?useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String pas = "root";
        //获取执行者
        conn = DriverManager.getConnection(url, user, pas);
        if (conn != null) {
            System.out.println("连接成功");
            //获取发送 SQL 的对象
            statement = conn.createStatement();
        }else {
            System.out.println("连接失败");
        }
    }

    public void updateStu() throws SQLException {
        String sql3="update studentinfo set Address='北京' where sex=1 and age>20";
        int result3 = statement.executeUpdate(sql3);
        if (result3!=0){
            System.out.println("修改数据成功！");
        }else {
            System.out.println("修改数据失败！");
        }
    }


    public void deleteStu() throws SQLException {
        String sql4="delete from studentinfo where subjects in ('环艺','英语')";
        int result4=statement.executeUpdate(sql4);
        if (result4!=0){
            System.out.println("删除数据成功！");
        }else {
            System.out.println("删除数据失败！");
        }
    }

    /**
     * 关闭所有
     *
     * @throws SQLException sqlexception异常
     */
    public void closeAll() throws SQLException {
        if (statement != null) {
            statement.close();
        }
        if (conn != null) {
            conn.close();
        }
        if (pstmt != null) {
            pstmt.close();
        }
    }
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        StuInfoTest s=new StuInfoTest();
        s.jdbc();
        s.updateStu();
        s.deleteStu();
        s.closeAll();

    }
}
